package com.example.bookshelf.data;

import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;


import androidx.annotation.RequiresApi;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.function.Predicate;

public class BookManager implements Serializable, Parcelable {
    private final ArrayList<BookItem> bookItems;
    private final ArrayList<BookLabel> bookLabels;
    private final ArrayList<Bookshelf> bookshelves;

    public BookManager(){
        bookItems = new ArrayList<>();
        bookLabels = new ArrayList<>();
        bookshelves = new ArrayList<>();
    }

    protected BookManager(Parcel in) {
        bookItems = in.createTypedArrayList(BookItem.CREATOR);
        bookLabels = in.createTypedArrayList(BookLabel.CREATOR);
        bookshelves = in.createTypedArrayList(Bookshelf.CREATOR);
    }

    public static final Creator<BookManager> CREATOR = new Creator<BookManager>() {
        @Override
        public BookManager createFromParcel(Parcel in) {
            return new BookManager(in);
        }

        @Override
        public BookManager[] newArray(int size) {
            return new BookManager[size];
        }
    };


// -------------------------------------------------------------------------------------------------
    // #############################
    // #根据条件（标签，书架）获得书本列表#
    // #############################
    public ArrayList<BookItem> getAllBooks() {
        return new ArrayList<>(bookItems);
    }

    public ArrayList<BookItem> getBooksByBookshelf(String name) {
        ArrayList<BookItem> output = new ArrayList<BookItem>();

        for(int i=0; i<bookItems.size(); i++) {
            Log.i("click", "getBooksByBookshelf: "+bookItems.get(i).getBookshelfName());
            if (bookItems.get(i).getBookshelfName().equals(name)) {
                output.add(bookItems.get(i));
            }
        }

        return output;
    }

    public ArrayList<BookItem> getBooksByLabel(String label) {
        ArrayList<BookItem> output = new ArrayList<BookItem>();

        for(int i=0; i<bookItems.size(); i++) {
            if (bookItems.get(i).getLabels().equals(label)) {
                output.add(bookItems.get(i));
            }
        }

        return output;
    }


// -------------------------------------------------------------------------------------------------
    // ##################
    // #删除书本，书架，标签#
    // ##################
    public void removeBook(BookItem bookItem){
        for (BookItem book : this.bookItems) {
            if (book == bookItem) {
                bookItems.remove(bookItem);
                break;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void removeBookshelf(Bookshelf bookshelf) {
        // 删除书籍中的书架
        for (BookItem book : this.bookItems) {
            if (book.getBookshelfName().equals(bookshelf.getName())) {
                book.setBookshelfName("");
            }
        }
        // 删除书架
        for (Bookshelf bookshelf_: this.bookshelves) {
            Log.i("tag", "removeBookshelf: " + bookshelf_.getName());
            Log.i("tag", "removeBookshelf: " + bookshelf.getName());

            if (bookshelf_.getName().equals(bookshelf.getName())) {
                this.bookshelves.removeIf(bookshelf1 -> bookshelf1.getName().equals(bookshelf.getName()));
//                break;
            }
        }
    }

    public void removeLabel(BookLabel bookLabel) {
        // 删除书籍中的标签
        for (BookItem book : this.bookItems) {
            if (book.getLabels().equals(bookLabel.getLabel())) {
                book.setLabels("");
            }
        }
        // 删除标签
        for (BookLabel bookLabel_: this.bookLabels) {
            if (bookLabel_ == bookLabel) {
                this.bookLabels.remove(bookLabel);
                break;
            }
        }
    }


// -------------------------------------------------------------------------------------------------
    // ####################
    // #对book items进行排序#
    // ####################
    static public void sortByTitle(ArrayList<BookItem> bookItems) {
        Collections.sort(bookItems, (bookItem, t1) -> bookItem.getTitle().compareTo(t1.getTitle()));
    }

    static public void sortByAuthor(ArrayList<BookItem> bookItems) {
        Collections.sort(bookItems, (bookItem, t1) -> bookItem.getAuthor().compareTo(t1.getAuthor()));
    }

    static public void sortByPress(ArrayList<BookItem> bookItems) {
        Collections.sort(bookItems, (bookItem, t1) -> bookItem.getPress().compareTo(t1.getPress()));
    }

    static public void sortByPublishedDate(ArrayList<BookItem> bookItems) {
        Collections.sort(bookItems, (bookItem, t1) -> {
            if (bookItem.getPublishedYear() != t1.getPublishedYear()) {

                return (bookItem.getPublishedYear()-t1.getPublishedYear())*50;
            }
            else {
                return bookItem.getPublishedMonth() - t1.getPublishedMonth();
            }
        });
    }


// -------------------------------------------------------------------------------------------------
    // ###########
    // 添加书架和标签
    // ###########
    static public boolean addBookshelf(ArrayList<Bookshelf> bookshelves, Bookshelf bookshelfAdd) {
        boolean flag = true;
        for (Bookshelf bookshelf:bookshelves) {
            if (bookshelf.getName().equals(bookshelfAdd.getName())) {
                flag = false;
                break;
            }
        }
        if (flag) {
            bookshelves.add(bookshelfAdd);
        }
        return flag;
    }

    static public boolean addBookLabel(ArrayList<BookLabel> bookLabels, BookLabel bookLabelAdd) {
        boolean flag = true;
        for (BookLabel bookLabel:bookLabels) {
            if (bookLabel.getLabel().equals(bookLabelAdd.getLabel())) {
                flag = false;
                break;
            }
        }
        if (flag) {
            bookLabels.add(bookLabelAdd);
        }
        return flag;
    }


// -------------------------------------------------------------------------------------------------
    // ######################
    // 获得书架后标签 List中的索引
    // ######################
    static public int getBookshelfPosition(ArrayList<Bookshelf> bookshelves, BookItem bookItem) {
        int position = 0;
        for (position=0; position<bookshelves.size(); position++) {
            if (bookItem.getBookshelfName().equals(bookshelves.get(position).getName())) {
                return position;
            }
        }
        return -1;
    }

    static public int getReadingStatePosition(BookItem bookItem) {
        String readingState = bookItem.getReadingStatus();
        if (readingState.equals("未读")){
            return 1;
        }
        else if (readingState.equals("阅读中")) {
            return 2;
        }
        else if (readingState.equals("已读")) {
            return 3;
        }
        else
            return 0;
    }


// -------------------------------------------------------------------------------------------------
    // ############################
    // 从bookItem的list中搜索特定关键词
    // ############################
    static public ArrayList<BookItem> searchBookItem(ArrayList<BookItem> bookItems, String keyWord) {
        ArrayList<BookItem> bookItems_return = new ArrayList<BookItem>();
        for (BookItem bookItem:bookItems) {
            if (bookItem.getTitle().contains(keyWord) ||
                bookItem.getAuthor().contains(keyWord) ||
                bookItem.getTranslator().contains(keyWord) ||
                bookItem.getPress().contains(keyWord)) {

                bookItems_return.add(bookItem);
                Log.i("function call", "searchBookItem: 1");
            }
        }
        Log.i("function call", "searchBookItem: ");
        return bookItems_return;
    }


// -------------------------------------------------------------------------------------------------
    // #############
    // 重命名书架、标签
    // #############
    public void renameBookshelf(String nameOld, String nameNew) {
        for (Bookshelf bookshelf : this.bookshelves) {
            if (bookshelf.getName().equals(nameOld)) {
                bookshelf.setName(nameNew);
            }
        }
        for (BookItem bookItem : this.bookItems) {
            if (bookItem.getBookshelfName().equals(nameOld)) {
                bookItem.setBookshelfName(nameNew);
            }
        }
    }

    public void renameBookLabel(String nameOld, String nameNew) {

    }


// -------------------------------------------------------------------------------------------------
    public ArrayList<BookItem> getBookItems() {
        return bookItems;
    }

    public ArrayList<BookLabel> getBookLabels() {
        return bookLabels;
    }

    public ArrayList<Bookshelf> getBookshelves() {
        return bookshelves;
    }


// -------------------------------------------------------------------------------------------------
    // ##############
    // 更新全部书架和标签
    // ##############
    public void updateBookLabels(ArrayList<BookLabel> bookLabels) {
        this.bookLabels.clear();
        this.bookLabels.addAll(bookLabels);
    }

    public void updateBookshelves(ArrayList<Bookshelf> bookshelves) {
        this.bookshelves.clear();
        this.bookshelves.addAll(bookshelves);
    }


// -------------------------------------------------------------------------------------------------

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeTypedList(bookItems);
        parcel.writeTypedList(bookLabels);
        parcel.writeTypedList(bookshelves);
    }
}
